package com.demo.java.pattern.stratege;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    private Map<OrderHandlerType, OrderPayHandler> maps = new HashMap<>();

    @Autowired
    public OrderServiceImpl(List<OrderPayHandler> maps) {
        this.maps = maps.stream().collect(Collectors.toMap(orderHandler ->
                AnnotationUtils.findAnnotation(orderHandler.getClass(), OrderHandlerType.class),
                v -> v, (v1, v2) -> v1));
    }

    public void pay(Order order) {
        OrderHandlerType orderHandlerType = new OrderHandlerTypeImpl(order);
        if (!maps.containsKey(orderHandlerType)) {
            throw new RuntimeException("not support payment.");
        }

        maps.get(orderHandlerType).handle(order);
    }
}
